const __util_path = require('path');
const __util_os = require('os');
const __util_fs = require('fs');
const __util_app = require('electron').remote.app;

const __util_start_path = __util_path.join(__dirname, '../..');

var __util_resolvePath = function (originPath) {
    return __util_path.join(__util_start_path, originPath);
}

var __util_getUserPath = function (path) {
    if (!path) {
        return __util_os.homedir();
    } else if (path.startsWith('~/')) {
        return __util_path.resolve(__util_os.homedir(), path.substr(2));
    } else if (path == '~') {
        return __util_os.homedir();
    } else {
        return path;
    }

}

const __util_config_path = __util_path.resolve(__util_os.homedir(), __util_app.getPath('documents'), 'mac-quick-start', 'config.json');
var __util_readConfig = function () {
    console.log(__util_config_path);
    if (!__util_fs.existsSync(__util_config_path)) {
        return {};
    }
    var data = __util_fs.readFileSync(__util_config_path, { encoding: "utf-8" });
    return JSON.parse(data);
}

var __util_saveConfig = function (data) {
    if (!__util_fs.existsSync(__util_path.dirname(__util_config_path))) {
        __util_fs.mkdirSync(__util_path.dirname(__util_config_path));
    }
    __util_fs.writeFileSync(__util_config_path, JSON.stringify(data, null, 4), { encoding: 'utf8' });
}

var __util_delDir = function(path){
    let files = [];
    if(fs.existsSync(path)){
        files = fs.readdirSync(path);
        files.forEach((file, index) => {
            let curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()){
                delDir(curPath); 
            } else {
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
}

module.exports.resolvePath = __util_resolvePath
module.exports.getUserPath = __util_getUserPath
module.exports.readConfig = __util_readConfig
module.exports.saveConfig = __util_saveConfig
module.exports.delDir = __util_delDir